#!/usr/bin/env python
# -*- coding:utf8 -*-
#
# created by shibaofeng@ipin.com 8/15/16
#
import cv2
import sys


def image_binary(cv_image, _type, threshold=127, maxval=255):
    """
    convert image to binary image
    :param cv_image: image from cv2.imread()
    :param _type: binary type
    :param threshold: threshold
    :param maxval: max value of image
    :return:
    """
    if _type == 'bininv':
        bt = cv2.THRESH_BINARY_INV
    elif _type == 'ostu':
        bt = cv2.THRESH_OTSU
    elif _type == 'tozero':
        bt = cv2.THRESH_TOZERO
    elif _type == 'trunc':
        bt = cv2.THRESH_TRUNC
    elif _type == 'tozeroinv':
        bt = cv2.THRESH_TOZERO_INV
    else:
        bt = cv2.THRESH_BINARY

    ret, thresh = cv2.threshold(cv_image, threshold, maxval, bt)
    return thresh


if __name__ == '__main__':
    if len(sys.argv) < 6:
        print '%s in out type threshold maxval' % __file__
    else:
        img = cv2.imread(sys.argv[1])
        bimg = image_binary(img, sys.argv[3], int(sys.argv[4]), int(sys.argv[5]))
        cv2.imwrite(sys.argv[2], bimg)
